<template>
	<page-header-wrapper :title="false">
		<el-card class="box-card">
			<div slot="header" class="table-page-search-wrapper">
				<a-form layout="inline">
					<a-row :gutter="48">
						<a-col :span="6">
							<a-form-item label="标题">
								<a-input v-model="queryParam.title" placeholder="请输入标题" />
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="分类">
								<a-tree-select v-model="queryParam.categoryId"
									:replaceFields="{children:'children', title:'name', key:'id', value: 'id' }" :tree-data="treeData"
									placeholder="请选择分类" tree-default-expand-all :dropdownMatchSelectWidth="true"
									:dropdown-style="{ maxHeight: '300px', overflow: 'auto' }">
									<span slot="title" slot-scope="{ key, value }" style="color: #08c">
										{{ value }}
									</span>
								</a-tree-select>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="状态">
								<a-select v-model="queryParam.state" placeholder="请选择状态">
									<a-select-option v-for="(item,index) in stateList" :key="index" :value="item.value">
										{{ item.label }}
									</a-select-option>
								</a-select>

							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-button style="margin-right: 8px" type="primary" @click="query">查询</a-button>
							<a-button type="danger" @click="reset">重置</a-button>
						</a-col>
						<a-col :offset="16" :span="8" style="text-align: right;">
							<span class="table-page-search-submitButtons">
								<a-button icon="plus" style="margin-right: 8px" type="primary" @click="handleAdd">新建</a-button>
							</span>
						</a-col>
					</a-row>
				</a-form>
			</div>
			<el-table :data="tableData" border style="width: 100%">
				<el-table-column width="150" label="分类" prop="categoryName" />
				<el-table-column width="200" label="标题" prop="title" />
				<el-table-column width="200" label="简介" prop="brief" />
				<el-table-column width="150" label="视频" align="center">
					<template slot-scope="scope">
						<el-link :underline="false" type="primary" @click="handleView(scope.row)">查看
						</el-link>
					</template>
				</el-table-column>
				<el-table-column width="150" label="状态" align="center">
					<template slot-scope="scope">
						<el-tag v-if="parseInt(scope.row.state) === 1">激活</el-tag>
						<el-tag v-if="parseInt(scope.row.state) === 2" type="danger">冻结</el-tag>
					</template>
				</el-table-column>
				<el-table-column width="150" label="排序号" prop="sortOrder" align="center" />
				<el-table-column width="150" label="创建时间" prop="createTime" align="center" />
				<el-table-column width="150" label="更新时间" prop="updateTime" align="center" />
				<el-table-column width="210" fixed="right" align="center" label="操作">
					<template slot-scope="scope">
						<el-link :underline="false" type="primary" @click="handleEdit(scope.row)">编辑
						</el-link>
						<el-link v-if="parseInt(scope.row.state) === 2" :underline="false" style="margin-left:10px;" type="success"
							@click="handleStatus(scope.row)">激活
						</el-link>
						<el-link v-if="parseInt(scope.row.state) === 1" :underline="false" style="margin-left:10px;" type="danger"
							@click="handleStatus(scope.row)">冻结
						</el-link>
						<el-link :underline="false" style="margin-left:10px;" type="info" @click="handleCopy(scope.row)">复制
						</el-link>
					</template>
				</el-table-column>
			</el-table>
			<div style="display: flex;justify-content: flex-end;margin: 20px 0 0;">
				<el-pagination :current-page="queryParam.page" :page-size="queryParam.limit" :page-sizes="[10, 20, 30, 40]"
					:total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
					@current-change="handleCurrentChange">
				</el-pagination>
			</div>
		</el-card>
		<a-modal :title="modal.title" :visible="modal.visible" maskClosable width="95%" @cancel="modal.visible = false"
			@ok="handleOk">
			<a-form :form="modal.form" :label-col="{ span: 2 }" :wrapper-col="{ span: 12 }">
				<a-form-item label="分类">
					<a-tree-select v-model="modal.form.categoryId"
						:replaceFields="{children:'children', title:'name', key:'id', value: 'id' }" :tree-data="treeData"
						placeholder="请选择分类" tree-default-expand-all :dropdownMatchSelectWidth="true"
						:dropdown-style="{ maxHeight: '300px', overflow: 'auto' }">
						<span slot="title" slot-scope="{ key, value }" style="color: #08c">
							{{ value }}
						</span>
					</a-tree-select>
				</a-form-item>
				<a-form-item label="封面">
					<!-- <a-upload :action="uploadApi" :show-upload-list="false" accept="image/png, image/jpeg" class="avatar-uploader"
            list-type="picture-card" name="file" @change="handleChange"> -->
					<a-upload action="#" :show-upload-list="false" name="file" accept="image/png, image/jpeg"
						class="avatar-uploader" list-type="picture-card" :customRequest="handleUploadCover">
						<img v-if="coverFileList && coverFileList[0]" :src="coverFileList[0].response.data.src" alt="avatar"
							height="150" width="150" />
						<div v-else>
							<a-icon type="plus" />
							<div class="ant-upload-text">
								上传
							</div>
						</div>
					</a-upload>
				</a-form-item>
				<a-form-item label="标题">
					<a-input v-model="modal.form.title" placeholder="请输入标题" />
				</a-form-item>
				<a-form-item label="简介">
					<a-textarea v-model="modal.form.brief" :auto-size="{ minRows: 2, maxRows: 6 }" placeholder="请输入简介" />
				</a-form-item>
				<a-form-item label="视频">
					<template v-if="modal.form.url === ''">
						<a-upload action="#" :showUploadList="false" name="file" :customRequest="handleUpload" accept="video/*">
							<a-button>
								<a-icon type="upload" />
								上传视频
							</a-button>
						</a-upload>
					</template>
					<template v-else>
						<div class="view-video">
							<video :src="modal.form.url" controls="controls" style="width: 100%;"></video>
							<div class="close" @click="modal.form.url = ''">
								<a-icon :style="{fontSize: '20px'}" theme="filled" type="close-circle" />
							</div>
						</div>
					</template>
				</a-form-item>
				<a-form-item label="标签">
					<el-tag v-for="(item,index) in dynamicTags" :key="index" :disable-transitions="false" closable
						style="margin-right: 15px" @close="handleClose(item)">
						{{ item }}
					</el-tag>
					<el-input v-if="inputVisible" ref="saveTagInput" v-model="inputValue" class="input-new-tag" maxlength="5"
						size="small" @blur="handleInputConfirm" @keyup.enter.native="handleInputConfirm">
					</el-input>
					<el-button v-else class="button-new-tag" size="small" @click="showInput">新增标签</el-button>
				</a-form-item>
				<a-form-item label="状态">
					<a-select v-model="modal.form.state" placeholder="请选择状态">
						<a-select-option v-for="(item,index) in stateList" :key="index" :value="item.value">
							{{ item.label }}
						</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item label="排序号">
					<a-input v-model="modal.form.sortOrder" placeholder="请输入排序号" />
				</a-form-item>
			</a-form>
		</a-modal>
	</page-header-wrapper>
</template>

<script>
	import {
		Loading
	} from 'element-ui';
	import {
		addContentVideo,
		getActiveTree as getTree,
		getTablePaiContentVideo,
		paiContentVideoActive,
		paiContentVideoFrozen,
		updateContentVideo
	} from '@/api/contentCenter'
	import api from '@/api/banner'
	import {
		getUploadForOSS,
		POST
	} from '@/api/banner'

	const baseApi = process.env.VUE_APP_API_BASE_URL

	export default {
		name: 'Index',
		data() {
			return {
				dynamicTags: [],
				inputVisible: false,
				inputValue: '',
				showPreview: false,
				stateList: [ {
					value: 1,
					label: '激活'
				}, {
					value: 2,
					label: '冻结'
				} ],
				queryParam: {
					page: 1,
					limit: 20
				},
				total: 0,
				typeId: 1,
				modal: {
					visible: false,
					title: '',
					form: {}
				},
				fileList: [],
				bannerLoading: false,
				coverFileList: [],
				uploadApi: baseApi + api.upload,
				treeData: [],
				tableData: []
			}
		},
		mounted() {
			this.getTable()
			this.getTree()
		},
		methods: {
			handleClose( tag ) {
				this.dynamicTags.splice( this.dynamicTags.indexOf( tag ), 1 )
			},
			showInput() {
				if ( this.dynamicTags.length === 3 ) {
					this.inputVisible = false
					this.$message( {
						message: '最多只能添加3个标签',
						type: 'warning'
					} )
					return
				}
				this.inputVisible = true
				this.$nextTick( _ => {
					this.$refs.saveTagInput.$refs.input.focus()
				} )
			},

			handleInputConfirm() {
				const inputValue = this.inputValue
				if ( inputValue ) {
					this.dynamicTags.push( inputValue )
				}
				this.inputVisible = false
				this.inputValue = ''
			},
			query() {
				this.queryParam.page = 1
				this.getTable()
			},
			reset() {
				this.queryParam = {
					page: 1,
					limit: 20
				}
				this.getTable()
			},
			handleView( record ) {
				window.open( record.url )
			},
			handleSizeChange( val ) {
				this.queryParam.limit = val
				this.getTable()
			},
			handleCurrentChange( val ) {
				this.queryParam.page = val
				this.getTable()
			},
			handleStatus( record ) {
				this.$confirm( `您确定要${record.state === 1 ? '冻结' : '激活'}吗？`, {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				} ).then( () => {
					if ( record.state === 1 ) {
						paiContentVideoFrozen( {
							id: record.id,
							state: 2
						} ).then( () => {
							this.$message.success( '冻结成功' )
							this.getTable()
						} )
					} else {
						paiContentVideoActive( {
							id: record.id,
							state: 1
						} ).then( () => {
							this.$message.success( '激活成功' )
							this.queryParam.page = 1
							this.getTable()
						} )
					}
				} ).catch( () => {} )
			},
			getTable() {
				getTablePaiContentVideo( this.queryParam ).then( res => {
					this.tableData = res.data.records
					this.total = parseInt( res.data.total )
				} )
			},
			getTree() {
				getTree( {
					page: 1,
					limit: 100000
				}, this.typeId ).then( res => {
					this.treeData = JSON.parse( JSON.stringify( res.data ) )
				} )
			},
			handleOk() {
				if ( this.modal.form.id ) {
					updateContentVideo( {
							label: this.dynamicTags.length > 0 ? this.dynamicTags.join() : '',
							...this.modal.form
						} )
						.then( res => {
							this.$message.success( res.msg )
							this.modal.form = {}
							this.modal.visible = false
							this.queryParam.page = 1
							this.getTable()
						} )
				} else {
					addContentVideo( {
							label: this.dynamicTags.length > 0 ? this.dynamicTags.join() : '',
							...this.modal.form
						} )
						.then( res => {
							this.$message.success( res.msg )
							this.modal.form = {}
							this.modal.visible = false
							this.queryParam.page = 1
							this.getTable()
						} )
				}
			},
			handleAdd() {
				this.modal.form = {
					categoryId: '',
					brief: '',
					cover: '',
					sortOrder: '100',
					typeId: this.typeId,
					url: '',
					title: '',
					state: 1
				}
				this.dynamicTags = []
				this.coverFileList = null
				this.modal.visible = true
				this.modal.title = '新增'
			},
			handleEdit( record ) {
				const data = JSON.parse( JSON.stringify( record ) )
				this.dynamicTags = data.labels
				this.modal.form = {
					categoryId: data.categoryId,
					brief: data.brief,
					cover: data.cover,
					sortOrder: data.sortOrder,
					typeId: data.typeId,
					url: data.url,
					title: data.title,
					state: data.state,
					id: data.id
				}
				this.coverFileList = [ {
					response: {
						data: {
							src: data.cover
						}
					}
				} ]
				this.modal.visible = true
				this.modal.title = '编辑'
			},
			handleCopy( record ) {
				const data = JSON.parse( JSON.stringify( record ) )
				this.dynamicTags = data.labels
				this.modal.form = {
					categoryId: data.categoryId,
					brief: data.brief,
					cover: data.cover,
					sortOrder: data.sortOrder,
					typeId: data.typeId,
					url: data.url,
					title: data.title,
					state: data.state
				}
				this.coverFileList = [ {
					response: {
						data: {
							src: data.cover
						}
					}
				} ]
				this.modal.visible = true
				this.modal.title = '复制'
			},
			normFile( e ) {
				if ( e.file.response && e.file.response.data ) {
					// this.form.setFieldsValue({ srcSave: e.file.response.data.srcSave })
					return e.file.response.data.src
				}
				return ''
			},

			// 视频上传，2024年11月5日23:54:28
			handleUpload( e ) {
				// if (e.file.status === 'uploading') {
				//   this.bannerLoading = true
				//   return
				// }
				// if (e.file.status === 'done') {
				//   const videoFileList = e.fileList.slice(-1)
				//   this.modal.form.url = videoFileList[0].response.data.src
				//   this.bannerLoading = false
				// }
				const loadingInstance = Loading.service( {
					background: 'rgba(0, 0, 0,0)'
				} )
				getUploadForOSS( {
					fileName: e.file.name
				} ).then( res => {
					if ( res.data ) {
						let data = res.data;
						const formData = new FormData();
						formData.append( "name", e.name );
						formData.append( "policy", data.policy );
						formData.append( "OSSAccessKeyId", data.ossAccessKeyId );
						formData.append( "success_action_status", "200" );
						formData.append( "signature", data.signature );
						formData.append( "key", data.fileKey );
						formData.append( "file", e.file );
						this.fileTooss( data.host, formData, res.data.saveFileUrl )
					}
				} ).catch( () => {
					loadingInstance.close()
				} )
			},

			fileTooss( url, formData, resultUrl ) {
				const loadingInstance = Loading.service( {
					background: 'rgba(0, 0, 0,0)'
				} )
				POST( url, formData )
					.then( ( res ) => {
						loadingInstance.close()
						if ( res.status == '200' ) {
							this.modal.form.url = resultUrl
							// this.bannerLoading = false
						}
					} )
					.catch( () => {
						loadingInstance.close()
					} )
			},

			// 封面，2024年11月5日23:54:28
			handleUploadCover( e ) {
				const loadingInstance = Loading.service( {
					background: 'rgba(0, 0, 0,0)'
				} )
				getUploadForOSS( {
					fileName: e.file.name
				} ).then( res => {
					if ( res.data ) {
						let data = res.data;
						const formData = new FormData();
						formData.append( "name", e.name );
						formData.append( "policy", data.policy );
						formData.append( "OSSAccessKeyId", data.ossAccessKeyId );
						formData.append( "success_action_status", "200" );
						formData.append( "signature", data.signature );
						formData.append( "key", data.fileKey );
						formData.append( "file", e.file );
						this.fileToossCover( data.host, formData, res.data.saveFileUrl )
					}
				} ).catch( () => {
					loadingInstance.close()
				} )
			},

			fileToossCover( url, formData, resultUrl ) {
				const loadingInstance = Loading.service( {
					background: 'rgba(0, 0, 0,0)'
				} )
				POST( url, formData )
					.then( ( res ) => {
						loadingInstance.close()
						if ( res.status == '200' ) {
							this.modal.form.cover = resultUrl
							this.coverFileList = [ {
								response: {
									data: {
										src: resultUrl
									}
								}
							} ]
						}
					} )
					.catch( () => {
						loadingInstance.close()
					} )
			},


			handleChange( info ) {
				if ( info.file.status === 'uploading' ) {
					this.bannerLoading = true
					return
				}
				if ( info.file.status === 'done' ) {
					this.coverFileList = info.fileList.slice( -1 )
					this.modal.form.cover = this.coverFileList[ 0 ].response.data.src
					this.bannerLoading = false
				}
			}
		}
	}
</script>

<style lang="less" scoped>
	.view-video {
		position: relative;

		.close {
			position: absolute;
			right: 15px;
			top: 0;
			cursor: pointer;
		}
	}

	/deep/.ant-modal-body {
		max-height: calc(80vh - 150px);
		overflow-y: auto;

		&::-webkit-scrollbar {
			width: 6px;
			/*高宽分别对应横竖滚动条的尺寸*/
			height: 1px;
		}

		&::-webkit-scrollbar-thumb {
			// -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
			background: #e3e3e6;
			border-radius: 6px;
		}

		&::-webkit-scrollbar-track {
			background: transparent;
			// -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
			border-radius: 5px;
		}
	}
</style>